// Contain
package Pigeon

import (
	"encoding/json"
	// "flag"
	"fmt"
	// "github.com/astaxie/beego/httplib"
	"github.com/golang/glog"
	"net/http"
)

type myServerHandler struct {
}

func Server() {
	myServerHandlerIns := new(myServerHandler)
	http.Handle("/", myServerHandlerIns)
	port := ":8080"
	glog.Infoln("serving on ", port, "...")
	http.ListenAndServe(port, nil)
}

// 接受消息
func (*myServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "text/javascript;charset=UTF-8")
	glog.Infoln("requesting....", r.URL.String())
	content := r.PostFormValue("content")
	qname := r.PostFormValue("qname")
	err := AddMessage(qname, content)
	ret := new(Result)
	if err == nil {
		ret.Code = 200
		ret.Msg = "success"
		ret.Result = 1
	} else {
		ret.Code = 3003
		ret.Msg = "error"
		ret.Result = 0
	}
	glog.Infoln("收到message", qname, content)
	retByte, err := json.Marshal(ret)
	if err == nil {
		fmt.Fprintf(w, string(retByte))
	} else {
		fmt.Fprintf(w, "Error %v", err.Error())
	}
}
